package com.lsy.weizhi2.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.lsy.weizhi2.JsonObject.MyCollectNote;
import com.lsy.weizhi2.JsonObject.NoteList;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.activity.ImageShow;
import com.lsy.weizhi2.adapter.HeadImageAdapter;
import com.lsy.weizhi2.adapter.ImageAdapterBig;
import com.lsy.weizhi2.adapter.MySendAdapter;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.mybase.BaseApp;
import com.lsy.weizhi2.myutils.NoteDetailUPCall;
import com.lsy.weizhi2.myutils.UserInfoCall;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.List;

/**
 * Created by 嗨哟 on 2017/3/15.
 */
public class NoteDetailUP extends RelativeLayout implements View.OnClickListener {
    private Context context;
    private RelativeLayout note_detail_gallery;
    private ViewPager note_detail_vp;
    private RecyclerView note_detail_up_rv;
    private UserInfo note_detail_user_info;
    private TextView note_detail_title, note_detail_time, note_detail_price,
            note_detail_period, note_detail_number, note_detail_image_num, note_detail_content,
            note_detail_money_num, note_detail_follow_num, note_detail_reply_num, note_detail_look_num,
            note_detail_report_num, dashang_tv;
    private HeadImageAdapter headImageAdapter;
    private NoteDetailUPCall noteDetailUPCall;
    private List<Bitmap>list;
    private View view;
    private int size;
    private ViewPager note_detail_vp_2;
    private ImageAdapterBig imageAdapterBig;

    public NoteDetailUP(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.weizhi_detail_up, this, true);
        AutoUtils.autoSize(view);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        note_detail_vp_2= (ViewPager) view.findViewById(R.id.note_detail_vp_2);
        note_detail_gallery = (RelativeLayout) view.findViewById(R.id.note_detail_gallery);//帖子图片画廊外框
        note_detail_user_info = (UserInfo) view.findViewById(R.id.note_detail_user_info);//用户信息
        note_detail_vp = (ViewPager) view.findViewById(R.id.note_detail_vp);//帖子图片画廊展示
        note_detail_up_rv = (RecyclerView) view.findViewById(R.id.note_detail_up_rv);//打赏头像集合
        note_detail_title = (TextView) view.findViewById(R.id.note_detail_title);//帖子标题
        note_detail_time = (TextView) view.findViewById(R.id.note_detail_time);//发帖时间
        note_detail_price = (TextView) view.findViewById(R.id.note_detail_price);//服务单价
        note_detail_period = (TextView) view.findViewById(R.id.note_detail_period);//有效期
        note_detail_number = (TextView) view.findViewById(R.id.note_detail_number);//已成交次数
        note_detail_image_num = (TextView) view.findViewById(R.id.note_detail_image_num);//图片数量
        note_detail_content = (TextView) view.findViewById(R.id.note_detail_content);//帖子内容
        note_detail_money_num = (TextView) view.findViewById(R.id.note_detail_money_num);//打赏人数
        note_detail_follow_num = (TextView) view.findViewById(R.id.note_detail_follow_num);//关注人数
        note_detail_reply_num = (TextView) view.findViewById(R.id.note_detail_reply_num);//回复数量
        note_detail_look_num = (TextView) view.findViewById(R.id.note_detail_look_num);//查看次数
        note_detail_report_num = (TextView) view.findViewById(R.id.note_detail_report_num);//举报次数
        dashang_tv = (TextView) view.findViewById(R.id.dashang_tv);//打赏文字
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        note_detail_up_rv.setLayoutManager(manager);
        note_detail_money_num.setOnClickListener(this);
        note_detail_follow_num.setOnClickListener(this);
        note_detail_reply_num.setOnClickListener(this);
        note_detail_report_num.setOnClickListener(this);
        note_detail_user_info.setUserInfoCall(new UserInfoCall() {
            @Override
            public void onClick(View view, int flag) {
                switch (flag){
                    case UserInfoCall.FOLLOW:
                        //调用关注接口

                        break;
                    case UserInfoCall.IMAGE:
                        //跳转用户信息界面
                        break;
                }
            }
        });
    }

    /**
     * 根据传入的对象加载相关数据
     */
    public void setUserInfo(String name,int avatar,String guanzhu) {
        note_detail_user_info.setContent(name,avatar,guanzhu);
    }

    /**
     * 根据传入数据设定帖子相关文字信息
     */
    public void setNoteInfo(NoteList.ListBean noteDetailBean) {
        if(noteDetailBean!=null){
            note_detail_title.setText(noteDetailBean.getTitle());//帖子标题
            note_detail_time.setText(noteDetailBean.getCreateTime());//发帖时间
            switch (noteDetailBean.getPriceMethod()){
                case 0:
                    note_detail_price.setText(noteDetailBean.getPrice()+"/次");//服务单价
                    break;
                case 1:
                    note_detail_price.setText(noteDetailBean.getPrice()+"/时");//服务单价
                    break;
                case 2:
                    note_detail_price.setText(noteDetailBean.getPrice()+"/天");//服务单价
                    break;
                case 3:
                    note_detail_price.setText(noteDetailBean.getPrice()+"/周");//服务单价
                    break;
                case 4:
                    note_detail_price.setText(noteDetailBean.getPrice()+"/月");//服务单价
                    break;
                case 5:
                    note_detail_price.setText(noteDetailBean.getPrice()+"/年");//服务单价
                    break;
            }
            note_detail_period.setText("长期有效");//有效期
            note_detail_number.setText(noteDetailBean.getDealCount()+"");//已成交次数
            note_detail_content.setText(noteDetailBean.getContent());//帖子内容
            note_detail_money_num.setText("100");//打赏人数
            note_detail_follow_num.setText("1000");//关注人数
            note_detail_reply_num.setText(noteDetailBean.getReplyCount()+"");//回复数量
            note_detail_look_num.setText(noteDetailBean.getClickCount()+"");//查看次数
        }else{
            note_detail_title.setText("帖子标题");//帖子标题
            note_detail_time.setText("2017年3月15日 12:00");//发帖时间
            note_detail_price.setText("100/次");//服务单价
            note_detail_period.setText("长期有效");//有效期
            note_detail_number.setText("已成交3次");//已成交次数
            note_detail_content.setText("帖子内容");//帖子内容
            note_detail_money_num.setText("100");//打赏人数
            note_detail_follow_num.setText("1000");//关注人数
            note_detail_reply_num.setText("1400");//回复数量
            note_detail_look_num.setText("2000");//查看次数
            note_detail_report_num.setText("举报");//举报次数
        }
    }

    public void setNoteInfo(MyCollectNote.ListBean.OrderBean listBean){
        if(listBean!=null){
            note_detail_title.setText(listBean.getTitle());//帖子标题
            note_detail_time.setText(listBean.getCreateTime());//发帖时间
            if(listBean.getPriceMethod()==0){//次
                note_detail_price.setText(listBean.getPrice()+"/次");//服务单价
            }else if(listBean.getPriceMethod()==1){//时
                note_detail_price.setText(listBean.getPrice()+"/时");//服务单价
            }else if(listBean.getPriceMethod()==2){//天
                note_detail_price.setText(listBean.getPrice()+"/天");//服务单价
            }
            note_detail_period.setText("长期有效");//有效期
            note_detail_number.setText(listBean.getDealCount()+"");//已成交次数
            note_detail_content.setText(listBean.getContent());//帖子内容
            note_detail_money_num.setText("0");//打赏人数
            note_detail_follow_num.setText("1000");//关注人数
            note_detail_reply_num.setText(listBean.getReplyCount()+"");//回复数量
            note_detail_look_num.setText(listBean.getClickCount()+"");//查看次数
            note_detail_report_num.setText("举报");//举报次数
        }else{
            note_detail_title.setText("帖子标题");//帖子标题
            note_detail_time.setText("2017年3月15日 12:00");//发帖时间
            note_detail_price.setText("100/次");//服务单价
            note_detail_period.setText("长期有效");//有效期
            note_detail_number.setText("已成交3次");//已成交次数
            note_detail_content.setText("帖子内容");//帖子内容
            note_detail_money_num.setText("100");//打赏人数
            note_detail_follow_num.setText("1000");//关注人数
            note_detail_reply_num.setText("1400");//回复数量
            note_detail_look_num.setText("2000");//查看次数
            note_detail_report_num.setText("举报");//举报次数
        }
    }

    /**
     * 打赏人员头像
     */
    public void setHeadImages() {
        headImageAdapter = new HeadImageAdapter(context, null);
        note_detail_up_rv.setAdapter(headImageAdapter);
    }

    /**
     * 帖子图片加载
     */
    public void setNoteImages(String[]str) {
        //设置ViewPager的布局
        Log.i("NoteDetailUp", "SCREEN_HEIGHT==" + BaseApp.REAL_HEIGHT);
        LayoutParams params = new LayoutParams(
                BaseApp.SCREEN_WIDTH * 5 / 10, BaseApp.REAL_HEIGHT * 380 / 1334);
        Log.i("NoteDetailUp", "height==" + params.height);
        /**** 重要部分  ******/
        //clipChild用来定义他的子控件是否要在他应有的边界内进行绘制。 默认情况下，clipChild被设置为true。 也就是不允许进行扩展绘制。
        note_detail_vp.setClipChildren(false);
        //父容器一定要设置这个，否则看不出效果
        note_detail_gallery.setClipChildren(false);
        if(str!=null){
            size=str.length;
            note_detail_image_num.setText("1/"+size);
        }
        note_detail_vp.setLayoutParams(params);
        //为ViewPager设置PagerAdapter
        note_detail_vp.setAdapter(new MyPagerAdapter(str));
        //设置ViewPager切换效果，即实现画廊效果
        note_detail_vp.setPageTransformer(true, new ZoomOutPageTransformer());
        //设置预加载数量
        note_detail_vp.setOffscreenPageLimit(2);
        //设置每页之间的左右间隔
        Log.i("NoteDetailUp", "SCREEN_WIDTH==" + BaseApp.SCREEN_WIDTH);
        note_detail_vp.setPageMargin(BaseApp.SCREEN_WIDTH * 10 / 750);
        note_detail_vp.addOnPageChangeListener(new MyOnPageChangeListener());
        //将容器的触摸事件反馈给ViewPager
        note_detail_gallery.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // dispatch the events to the ViewPager, to solve the problem that we can swipe only the middle view.
                return note_detail_vp.dispatchTouchEvent(event);
            }

        });
    }
    private int position;
    public void setNoteImage2(final int[]str){
        if(str!=null&&str.length!=0){
            size=str.length;
            note_detail_image_num.setText("1/"+size);
        }
        imageAdapterBig = new ImageAdapterBig(context,str);
        note_detail_vp_2.setAdapter(imageAdapterBig);

        note_detail_vp_2.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                position=i;
                note_detail_image_num.setText(i + 1 + "/"+size);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    public void setNoteDetailUPCall(NoteDetailUPCall noteDetailUPCall) {
        this.noteDetailUPCall = noteDetailUPCall;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.note_detail_money_num:
                noteDetailUPCall.onClickFollow(view, NoteDetailUPCall.DASHANG);
                break;
            case R.id.note_detail_follow_num:
                noteDetailUPCall.onClickFollow(view, NoteDetailUPCall.FOLLOW_NOTE);
                break;
            case R.id.note_detail_reply_num:
                noteDetailUPCall.onClickFollow(view, NoteDetailUPCall.REPLY);
                break;
            case R.id.note_detail_report_num:
                noteDetailUPCall.onClickFollow(view, NoteDetailUPCall.REPORT);
                break;
            case R.id.activity_detail_reply_num://活动回复
                noteDetailUPCall.onClickFollow(view, NoteDetailUPCall.ACTIVITY_REPLY);
                break;
        }
    }
    ImageView imageView;
    class MyPagerAdapter extends PagerAdapter {
        private String[]str;

        public MyPagerAdapter(String[]str) {
            this.str = str;
        }

        @Override
        public int getCount() {
            //return viewList==null?0:viewList.size();
            return str==null?1:str.length;//ViewPager里的个数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if(str==null){
                imageView.setImageResource(R.mipmap.nopic);
            }else{
                Glide.with(context)
                        .load(new GlideUrl(Constants.DOWN_USER_PICTURE+str[position],new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(imageView);
            }
            ((ViewPager) container).addView(imageView);
            return imageView;

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
            //这里做切换ViewPager时，底部RadioButton的操作
            note_detail_image_num.setText(position + 1 + "/"+size);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (note_detail_gallery != null) {
                note_detail_gallery.invalidate();
            }
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    /**
     * 实现的原理是，在当前显示页面放大至原来的MAX_SCALE
     * 其他页面才是正常的的大小MIN_SCALE
     */
    class ZoomOutPageTransformer implements ViewPager.PageTransformer {
        private static final float MAX_SCALE = 1.2f;
        private static final float MIN_SCALE = 0.8f;//0.85f

        @Override
        public void transformPage(View view, float position) {
            //setScaleY只支持api11以上
            if (position < -1) {
                view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);
            } else if (position <= 1) //a页滑动至b页 ； a页从 0.0 -1 ；b页从1 ~ 0.0
            { // [-1,1]
//              Log.e("TAG", view + " , " + position + "");
                float scaleFactor = MIN_SCALE + (1 - Math.abs(position)) * (MAX_SCALE - MIN_SCALE);
                view.setScaleX(scaleFactor);
                //每次滑动后进行微小的移动目的是为了防止在三星的某些手机上出现两边的页面为显示的情况
                if (position > 0) {
                    view.setTranslationX(-scaleFactor * 2);
                } else if (position < 0) {
                    view.setTranslationX(scaleFactor * 2);
                }
                view.setScaleY(scaleFactor);

            } else { // (1,+Infinity]

                view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);

            }
        }

    }
}

